<template>
  <div class="private-message-container">
    <!-- 左侧：搜索框和对话列表 -->
    <div class="private-left-panel">
      <div class="search-container">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索联系人（姓名/电话/角色）"
            class="search-input"
            @keyup.enter.native="handleSearch"
        >
          <template #prefix>
            <el-icon @click="handleSearch" class="search-icon"><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 所有对话 -->
      <div v-if="allConversations.length > 0" class="conversation-section">
        <div class="section-title">所有对话 ({{ allConversations.length }})</div>
        <div
            v-for="conversation in allConversations"
            :key="conversation.id"
            :class="conversation.isReadCon ? 'conversation-card' : 'conversation-card unread'"
            @click.stop="openConversation(conversation)"
        >
          <el-avatar
              :size="48"
              :src="conversation && conversation.starterId===currentUser.id ? conversation.participant.avatar : conversation.starter.avatar"
              class="conversation-avatar"
          />
          <div class="conversation-content">
            <div class="conversation-name">{{conversation && conversation.starterId===currentUser.id ? conversation.participant.name : conversation.starter.name}}</div>
            <div class="conversation-preview">{{ conversation && conversation.latestMessage.content || '暂无消息' }}</div>
          </div>
          <div class="conversation-time">{{ conversation && formatDateTime(conversation.latestMessage.messageTime).display }}</div>

          <el-badge
              :value="conversation.unreadCount"
              :max="99"
              :class="{'unread-badge': conversation.unreadCount > 0}"
              v-if="conversation.unreadCount > 0"
          />
        </div>
      </div>

      <!-- 搜索结果 -->
      <div v-if="searchResults.length > 0 && showSearchResults" class="search-results-section">
        <div class="section-title">搜索结果</div>
        <div
            v-for="contact in searchResults"
            :key="contact.id"
            class="search-result-card"
            @click.stop="startNewConversation(contact)"
        >
          <el-avatar :size="48" :src="contact.doctorAvatar || defaultAvatar2" class="search-avatar" />
          <div class="search-content">
            <div class="search-name">{{ contact.name }}</div>
            <div class="search-info">{{ contact.contactPhone || '无电话' }} - {{ contact.role.roleName || '无角色' }}</div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!showSearchResults && (unreadConversations.length)" description="暂无私信消息" />
    </div>

    <!-- 右侧：对话框 -->
    <div class="private-right-panel" v-if="currentConversation">
      <div class="chat-header">
        <el-avatar
            v-if="!isLoading"
            :size="40"
            :src="currentConversation.starterId===currentUser.id ? currentConversation.participant.avatar : currentConversation.starter.avatar"
        />
        <div v-if="!isLoading" class="chat-title">{{ currentConversation.starterId===currentUser.id ? currentConversation.participant.name : currentConversation.starter.name }}</div>
        <div class="chat-actions">
          <el-button type="danger" @click="deleteConversation">删除对话</el-button>
          <el-button type="primary" @click="closeConversation">关闭对话</el-button>
          <el-button type="warning" @click="closeChat">退出聊天</el-button>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="chat-messages" ref="messageContainer">
        <div
            v-for="msg in currentConversation.messages || []"
            :key="msg.id"
            class="chat-message"
            :class="{ 'is-sender': msg.senderId === currentUser.id, 'is-receiver': msg.senderId !== currentUser.id }"
        >
          <!-- 对方消息（左侧） -->
          <div v-if="msg.senderId!==currentUser.id" class="message-wrapper receiver-message">
            <el-avatar
                :size="36"
                :src="msg.sender.avatar"
                class="message-avatar"
            />
            <div class="message-content">
              <div class="message-name">{{ msg.sender.name }}</div>
              <div class="message-text message-bubble receiver-bubble">
                {{ msg.content }}
              </div>
              <div class="message-time">{{ formatDateTime(msg.messageTime).display }}</div>
            </div>
          </div>
          <!-- 自己的消息（右侧） -->
          <div v-if="msg.senderId===currentUser.id"  class="message-wrapper sender-message">
            <el-avatar
                :size="36"
                :src="currentUser.doctorAvatar || defaultAvatar2"
                class="message-avatar"
            />
            <div class="message-content">
              <div class="message-name">{{ currentUser.username }}</div>
              <div class="message-text message-bubble sender-bubble">
                {{ msg.content }}
              </div>
              <div class="message-time">{{ formatDateTime(msg.messageTime).display }}</div>
            </div>
          </div>

        </div>
      </div>

      <!-- 输入框 -->
      <div class="chat-input-container">
        <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="2"
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
            class="chat-input"
        />
        <div class="chat-actions">
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </div>

    </div>

    <!-- 无对话选中状态 -->
    <el-empty v-else class="no-conversation" description="请选择一个联系人开始对话" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { Search } from '@element-plus/icons-vue';
import axios from "axios";
import { formatDateTime } from "/src/utils/dateUtil.js";
import {ElMessage, ElMessageBox} from 'element-plus';
import { userInfo } from '../../stores/index.js';
import { messageStore } from '../../stores/message.js';

const router = useRouter();
const userItemStore = userInfo();
const messageItemStore = messageStore();

// 从store获取数据
const currentUser = userItemStore.user;
const allConversations = messageItemStore.allConversations;


// 本地状态
const searchKeyword = ref('');
const searchResults = ref([]);
const showSearchResults = ref(false);
const currentConversation = ref({
  id:null,
  participantId: null,
  participant:{},
  starterId: null,
  starter:{},
  lastMessageId: null,
  lastMessage:{
    content:'',
    messageTime:null,
    senderId:null
  },
  isReadCon:null,
  unreadCount:null,
  createTime:null,
  updateTime:null,
  messages:[]
});
const inputMessage = ref('');
const messageContainer = ref(null);




// 计算属性：未读/已读对话
// 优化后的未读/已读对话计算
const unreadConversations = messageItemStore.unreadConversations;


// 修改 loadConversationMessages 方法
// 在script setup中添加加载状态
const isLoading = ref(true);

// 在加载对话数据的地方更新加载状态
const loadConversationMessages = async (conversationId) => {
  if (!conversationId) return;

  isLoading.value = true; // 开始加载时设为true

  try {
    const response = await axios.get(`/message/getMessagesByConversationId/${conversationId}`);
    currentConversation.value.messages = response.data || [];


  } catch (error) {
    ElMessage.error('加载消息失败，请稍后再试');
  } finally {
    isLoading.value = false; // 无论成功失败，最终设为false
  }
};

// 处理搜索
const handleSearch = () => {
  if (searchKeyword.value.trim() === '') {
    searchResults.value = [];
    showSearchResults.value = false;
    return;
  }

  const formKeyword = {
    teamId: null,
    keyword: searchKeyword.value
  };

  axios.post(`/doctor/getAllDoctors`, formKeyword)
      .then(resp => {
        searchResults.value = resp.data || [];
        showSearchResults.value = searchResults.value.length > 0;
      })
      .catch(error => {
        console.error('搜索失败:', error);
        ElMessage.error('搜索失败，请稍后再试');
      });
};

// 打开对话
const openConversation = (conversation) => {

  //将未读对话改成已读对话
  currentConversation.value = conversation;
  if (currentConversation.value.unreadCount >0) {
    currentConversation.value.unreadCount = 0;
    currentConversation.value.isReadCon = 1;

    markAsRead(conversation.id);

  }
  nextTick(async () => {
    await loadConversationMessages(conversation.id);
    scrollToLatestMessage();
  });

  showSearchResults.value = false;
};

// 开始新对话
const conversationData=ref({
  participantId:null,
  starterId:null,
});

const startNewConversation = async (contact) => {
  // 检查是否已有对话
  const existingConversation = allConversations.find(
      c => c.participantId === contact.id || c.starterId === contact.id
  );

  if (existingConversation) {
    // 已有对话，直接打开
    currentConversation.value = existingConversation;
    await loadConversationMessages(existingConversation.id);
  } else {
    conversationData.value.participantId = contact.id;
    conversationData.value.starterId = currentUser.id;
    try {
      // 创建新对话API调用
      const response = await axios.post(`/conversation/createConversation`, conversationData.value);

      const newConversation = response?.data;
      if (!newConversation) {
        throw new Error('创建对话返回数据异常');
      }

      // 补充必要字段（如果API未返回）
      newConversation.latestMessage = {
        content: '开始了新对话',
        messageTime: new Date()
      };
      // newConversation.unreadCount = newConversation.unreadCount || 0;
      // newConversation.isReadCon = newConversation.isReadCon || 1;

      // 使用Pinia store的方法更新对话列表（推荐方式）
      // messageItemStore.addConversation(newConversation);

      // 或直接操作数组并触发响应式更新
      // allConversations.push(newConversation); // 如果allConversations是ref
      messageItemStore.allConversations.push(newConversation); // 如果allConversations是ref

      // 更新当前对话
      currentConversation.value = newConversation;
      currentConversation.value.starter = currentUser;
      currentConversation.value.participant = contact;

      ElMessage.success('对话创建成功');

      // 强制视图更新
      nextTick(() => {});
    } catch (error) {
      console.error('创建对话失败', error);
      ElMessage.error('对话创建失败，请稍后再试');
    }
  }
  showSearchResults.value = false;
};

// 关闭对话
const closeConversation = () => {
  currentConversation.value = null;
};

// 退出聊天，返回上一页
const closeChat = () => {
  router.go(-1);
};

// 发送消息
const sendMessage = async () => {
  if (!currentConversation.value || inputMessage.value.trim() === '') {
    return;
  }

  try {
    // 构造消息数据
    const messageData = {
      senderId: currentUser.id,
      senderName: currentUser.username,
      senderAvatar: currentUser.doctorAvatar || defaultAvatar2,
      content: inputMessage.value,
      conversationId: currentConversation.value.id
    };

    // 调用API发送消息
    const response = await axios.post(`/message/saveMessage`, messageData);

    // 检查响应状态码
    if (!response || response.status !== 200) {
      throw new Error('API响应状态异常');
    }

    const responseData = response.data;
    const newMessage = responseData || {};
    // 更灵活的数据验证
    if (!newMessage.id) {
      throw new Error('API返回数据缺少必要字段');
    }

    // 添加到当前对话
    if (!currentConversation.value.messages) {
      currentConversation.value.messages = [];
    }

    currentConversation.value.messages.push(newMessage);

    // 更新对话最新消息和时间
    currentConversation.value.latestMessage.content = newMessage.content;
    currentConversation.value.latestMessage.messageTime = newMessage.messageTime;
    currentConversation.value.latestMessage.senderId = newMessage.senderId;

    // 清空输入框
    inputMessage.value = '';


    // 滚动到最新消息
    nextTick(() => {
      scrollToLatestMessage();
    });
    ElMessage.success('消息发送成功');
  } catch (error) {
    console.error('发送消息失败:', error);
  }
};

// 标记对话为已读
const markAsRead = async (conversationId) => {
  try {
    // 后端更新，调用API标记为已读
    await axios.put(`/conversation/markAsRead/${conversationId}/${currentUser.id}`);

    //pinia更新， 创建新数组，替换特定元素
    messageItemStore.allConversations = messageItemStore.allConversations.map(conversation => {
      if (conversation.id === conversationId) {
        // 创建新对象，保留其他属性
        return {
          ...conversation,
          isReadCon: 1,
          unreadCount: 0
        };
      }
      return conversation;
    });
    messageItemStore.updateUnreadConversations();

  } catch (error) {
    ElMessage.error('标记消息为已读失败');
  }
};

// 滚动到最新消息
const scrollToLatestMessage = () => {
  const container = messageContainer.value;
  if (container && container.scrollHeight) {
    container.scrollTop = container.scrollHeight;
  }
};

// 删除对话
const deleteConversation = async () => {
  // 检查当前是否有选中的对话
  if (!currentConversation.value) return;

  try {
    // 调用 ElMessageBox.confirm 显示确认对话框
    // 该方法返回 Promise，用户点击确认或取消时会 resolve 对应字符串
    const action = await ElMessageBox.confirm(
        `确定要删除此对话吗？删除后将无法恢复消息记录？`,
        'warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    // 如果用户点击取消，直接返回
    if (action !== 'confirm') {
      return;
    }

    // 调用后端API删除对话
    await axios.delete(`/conversation/deleteConversation/${currentConversation.value.id}`);

    // 获取当前对话ID并查找其在对话列表中的索引
    const conversationId = currentConversation.value.id;
    const conversationIndex = allConversations.findIndex(
        convo => convo.id === conversationId
    );

    // 从本地状态中删除对话
    if (conversationIndex !== -1) {
      allConversations.splice(conversationIndex, 1);
      ElMessage.success('对话删除成功');
    }

    // 关闭当前对话，显示空状态
    closeConversation();

  } catch (error) {
    // 处理异常情况（如网络错误、用户通过ESC关闭对话框等）
    console.error('删除对话操作异常:', error);

    // 仅当非用户取消操作时显示错误提示
    if (error !== 'cancel') {
      ElMessage.error('删除对话失败，请稍后再试');
    }
  }
};



// 监听当前对话变化
watch(
    currentConversation,
    (newConversation, oldConversation) => {
      if (newConversation !== oldConversation && oldConversation) {
        // 离开对话时标记为已读（如果有未读消息）
        if (oldConversation.unreadCount > 0) {
          markAsRead(oldConversation.id);
        }
      }
    },
    { deep: true }
);

// 监听对话列表变化
watch(
    allConversations,
    (newConversations) => {
      nextTick(() => {
        // 如果没有选中的对话且有对话存在，自动打开第一个对话
        if (newConversations.length > 0 && !currentConversation.value) {
          openConversation(newConversations[0]);
        }
      });
    },
    { deep: true }
);

// 组件挂载时初始化
onMounted(() => {

  // console.log('私信界面初始化完成');
  // // 确保store已加载对话数据
  // if (allConversations.length > 0 && !currentConversation.value) {
  //   openConversation(allConversations[0]);
  // }

});
</script>

<style scoped>
/* 私信容器 */
.private-message-container {
  display: flex;
  height: 100vh;
  min-height: 600px;
}

/* 左侧面板 */
.private-left-panel {
  width: 30%;
  border-right: 1px solid #eee;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background-color: #f9f9f9;
}

/* 右侧面板 */
.private-right-panel {
  width: 70%;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #eee;
  background-color: #fff;
}

/* 搜索容器 */
.search-container {
  padding: 10px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
}

.search-input {
  width: 100%;
}

.search-icon {
  cursor: pointer;
  color: #909399;
  transition: color 0.2s;
}

.search-icon:hover {
  color: #409eff;
}

/* 对话列表 */
.conversation-section {
  padding: 10px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #666;
  font-size: 14px;
}

.conversation-card {
  padding: 10px;
  display: flex;
  visibility: visible;
  align-items: center;
  cursor: pointer;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 8px;
  transition: background-color 0.2s;
  position: relative;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.conversation-card.unread {
  background-color: #e6ffed;
  border-left: 3px solid #52c41a;
  box-shadow: 0 2px 4px rgba(82, 196, 26, 0.1);
}

.conversation-card:hover {
  background-color: #f5f5f5;
}

.conversation-avatar {
  margin-right: 10px;
}

.conversation-content {
  flex: 1;
  min-width: 0;
}

.conversation-name {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-preview {
  color: #666;
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-time {
  color: #999;
  font-size: 12px;
  margin-left: 10px;
  min-width: 80px;
  text-align: right;
}

.unread-badge {
  position: absolute;
  right: 10px;
  top: 10px;
}

/* 搜索结果 */
.search-results-section {
  padding: 10px;
  border-top: 1px solid #eee;
}

.search-result-card {
  padding: 10px;
  display: flex;
  align-items: center;
  cursor: pointer;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 8px;
  transition: background-color 0.2s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.search-result-card:hover {
  background-color: #f5f5f5;
}

.search-avatar {
  margin-right: 10px;
}

.search-content {
  flex: 1;
}

.search-name {
  font-weight: 500;
}

.search-info {
  color: #666;
  font-size: 12px;
}

/* 聊天头部 */
.chat-header {
  padding: 10px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f9f9f9;
}

.chat-title {
  font-weight: 500;
  margin-left: 10px;
  flex: 1;
}

/* 消息列表 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f5f5;
}

.chat-message {
  display: flex;
  margin-bottom: 15px;
  width: 100%;
}

.message-wrapper {
  display: flex;
  align-items: flex-end;
  max-width: 80%;
}

/* 接收者消息 (左侧) */
.receiver-message {
  justify-content: flex-start;
  margin-right: auto;
}

/* 发送者消息 (右侧) */
.sender-message {
  justify-content: flex-end;
  margin-left: auto;
}

.message-avatar {
  margin: 0 8px;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 90%;
}

.sender-message .message-content {
  align-items: flex-end;
}

.receiver-message .message-content {
  align-items: flex-start;
}

.message-bubble {
  padding: 8px 12px;
  border-radius: 18px;
  margin-bottom: 3px;
  max-width: 100%;
  word-wrap: break-word;
}

.sender-bubble {
  background-color: #409EFF;
  color: white;
  border-radius: 18px 18px 0 18px;
}

.receiver-bubble {
  background-color: cornsilk;
  color: #333;
  border-radius: 18px 18px 18px 0;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 2px;
}

.message-name {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

/* 输入框 */
.chat-input-container {
  padding: 10px;
  border-top: 1px solid #eee;
  background-color: #fff;
}

.chat-input {
  width: 100%;
  margin-bottom: 10px;
}

.chat-actions {
  display: flex;
  justify-content: flex-end;
}

/* 空状态 */
.no-conversation {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>